/**
 * 点击粘贴
 * @param e
 * @param message
 */
export const handleUploadFileJqb = (e: HTMLElement, message = true) => {
  console.log(e);
  navigator.clipboard
    .read()
    .then((res) => {
      const clipboardItems = res[0];
      console.log(clipboardItems);
      // 判断剪切板内容是否为图片
      if (clipboardItems.types[0].indexOf("image") > -1) {
        // 得到blob对象（异步的）
        clipboardItems.getType(clipboardItems.types[0]).then((b) => {
          // blob转换为file对象
          const files = new window.File(
            [b],
            `${Math.floor(Math.random() * 2147483648).toString(36)}.png`,
            { type: clipboardItems.types[0] }
          );
          console.log(files);
        });
      } else {
        console.log(clipboardItems);
        if (clipboardItems.types[0].indexOf("text") > -1) {
          clipboardItems.getType(clipboardItems.types[0]).then((blob) => {
            blob.text().then(function (text) {
              console.log("文字是" + text);
            });
          });
        } else {
          message && ElMessage.error("请粘贴图片或者图片地址");
        }
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

/**
 * 获取 crit+v的内容
 * @param e
 */
export const keyUpV = () => {
  console.log(e);
  var clipboardData = e.clipboardData;
  // 如果是 Safari 直接 return
  if (!(e.clipboardData && e.clipboardData.items)) {
    return;
  }
  for (var i = 0; i < clipboardData.items.length; i++) {
    var item = clipboardData.items[i];
    console.log(item.kind);
    console.log(item);
    if (item.kind == "file" && item.type.indexOf("image") > -1) {
      var blob = item.getAsFile();
      console.log('类型')
      console.log(item)
      console.log(blob);
      if (blob.size === 0) {
        return;
      }

      break;
    } else if (item.kind == "string") {
      let text = clipboardData.getData("text");


    }
  }
};
interface FileInputFace {
  accept?: string
  multiple?: boolean
  isString?: boolean
}

export const createInput = (options: FileInputFace = {}): Promise<File[]> => {
  const { accept = '*', multiple = false, isString = false } = options;
  console.log("创建Input");
  return new Promise((resolve, reject) => {
    var input: HTMLInputElement = document.createElement("input"); // 创建一个 a 标签
    input.accept = accept;
    input.type = "file";
    input.multiple = multiple;
    input.onchange = (e: any) => {
      if (isString) {
        resolve(e.target.files[0])
      } else {
        resolve(e.target.files);
      }

    };
    document.body.appendChild(input);
    input.click();
    function monitor() {
      document.removeEventListener("mousemove", monitor);
      document.body.removeChild(input);
    }
    document.addEventListener("mousemove", monitor, false);
  });
};
interface objCompressed {
  width?: any;
  height?: any;
}

/**
 * 把base64转file或者 url
 * file用于web， url 用于小程序类
 * @param dataurl base64
 * @param filename 名字
 * @returns
 */
export function dataURLtoFile(
  dataurl: any,
  filename: any = Date.now() + "",
  type: string = "file"
): File {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  if (type == "file") {
    return new File([u8arr], filename, {
      type: mime,
    });
  } else {
    var url = URL || webkitURL;
    return url.createObjectURL(new Blob([u8arr], { type: mime }));
  }
}



/**
 * 压缩图片
 * @param {file} file 文件file
 * @param {*} objCompressed objCompressed 可传图片宽高,高默认同比例
 * @returns
 */
export function compressImgs(
  file: File,
  objCompressed: objCompressed,
  type: string = "file"
): Promise<File> {
  console.log(objCompressed);
  return new Promise((resolve, reject) => {
    const windowURL = window.URL || window.webkitURL;
    const src = windowURL.createObjectURL(file);
    var img = new Image();
    img.src = src;

    img.onload = function (e: any) {
      var that: any = this;
      //默认压缩后图片规格
      var quality = 0.7;
      var wd = that.width;
      var hd = that.height;
      var scale = wd / hd;
      //实际要求
      let w = objCompressed.width || wd;
      if (w > wd) {
        w = wd
      }
      const h = objCompressed.height || w / scale;
      //生成canvas
      var canvas = document.createElement("canvas");
      var ctx: any = canvas.getContext("2d");
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      var base64 = canvas.toDataURL("image/jpeg", quality);
      const url = dataURLtoFile(base64, file.name, type);
      // 回调函数返回base64的值
      resolve(url);
    };
  });
}


interface FileOption {
  isZip?: true,
  width?: number
}

export const getFileArrayBuffer = (file: File, option: FileOption = {}): Promise<ArrayBuffer | string> => {
  const { width = 750, isZip = true } = option
  return new Promise(async (resolve, reject) => {
    if (isZip) {
      file = await compressImgs(file, {
        width
      })


    }

    var reader = new FileReader();
    reader.onload = function (event) {
      var fileData = event.target?.result || ''; // 读取文件内容
      if (!fileData) {
        reject('未读取到文件内容')
      } else {
        resolve(fileData)
      }
    };
    reader.onerror = (err) => {
      reject(err)
    }
    reader.readAsArrayBuffer(file); // 以ArrayBuffer格式读取文件内容
  })
}